<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class ChangeCategory extends Model
{


    // 表名
    protected $name = 'change_category';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text'
    ];


    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public static function getStatusText($status)
    {
        $statusArr = [
            '0' => '开启',
            '1' => '关闭',
        ];
        return isset($statusArr[$status]) ? $statusArr[$status] : false;
    }

    /**
     * 列表
     */
    public static function getList($postData)
    {
        $where = '1=1';
        $order = 'a.id desc';
        $page = isset($postData['page']) && !empty($postData['page']) ? intval($postData['page']) : 1;
        $limit = isset($postData['limit']) && !empty($postData['limit']) ? intval($postData['limit']) : 10;
        $start = ($page - 1) * $limit;
        $field = "a.id, a.name, a.createtime, a.status";

        $list = db('change_category')
            ->alias('a')
            ->where($where)
            ->order($order)
            ->limit($start, $limit)
            ->field($field)
            ->select();
        if (!empty($list)) {
            foreach ($list as &$v) {
                $v['createtimeText'] = isset($v['createtime']) && !empty($v['createtime']) ? date('Y-m-d H:i:s', $v['createtime']) : '';
                $v['statusText'] = isset($v['status']) ? self::getStatusText($v['status']) : '';
            }
            unset($v);
        }

        $total = db('change_category')
            ->alias('a')
            ->where($where)
            ->count();

        return [
            'list' => $list,
            'total' => $total,
        ];

    }

    /**
     * 新增
     * @param $postData
     * @return bool
     */
    public static function addRow($postData)
    {
        $data = [
            'name' => $postData['name'],
            'status' => $postData['status'],
            'createtime' => time(),
            'updatetime' => time(),
        ];

        Db::startTrans();
        try {
            ChangeCategory::insert($data, true);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

        return true;
    }

    /**
     * 修改
     * @param $postData
     * @return bool
     */
    public static function updateRow($postData)
    {
        $data = [
            'name' => $postData['name'],
            'status' => $postData['status'],
            'updatetime' => time(),
        ];

        Db::startTrans();
        try {
            ChangeCategory::update($data, ['id'=>$postData['id']]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

        return true;
    }

    /**
     * 删除
     * @param $postData
     * @return bool
     */
    public static function deleteRow($postData)
    {
        Db::startTrans();
        try {
            // 删除变更分类时更新变更功能
            ChangeCategory::deleteRelationChangeFunction($postData['id']);

            ChangeCategory::where(['id'=>$postData['id']])->delete();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }

        return true;
    }

    /**
     * 删除相关变更分类
     * @param $id
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function deleteRelationChangeFunction($id)
    {
        $allChangeFunction = ChangeFunction::getAll();
        if(isset($allChangeFunction['list']) && !empty($allChangeFunction['list']))
        {
            foreach($allChangeFunction['list'] as $v)
            {
                if(!empty($v['change_category_id']) && $v['change_category_id'] == $id)
                {
                    db('change_function')->where("id={$v['id']}")->delete();
                }
            }
        }
    }

    /**
     * 所有
     * @return array
     */
    public static function getAll()
    {
        $where = '1=1 and status="0"';
        $order = 'a.id asc';
        $field = "a.id, a.name";

        $list = db('change_category')
            ->alias('a')
            ->where($where)
            ->order($order)
            ->field($field)
            ->select();

        return [
            'list' => $list,
        ];

    }

    public static function getInfo($where)
    {
        $field = "b.document, b.variables";
        $info = db('change_category')
            ->alias('a')
            ->join('change_function b', 'a.id=b.change_category_id')
            ->where($where)
            ->field($field)
            ->find();
        if(!empty($info) && isset($info['variables']) && !empty($info['variables'])) {
            $info['variablesList'] = db('variable')
                ->where("id", 'in', $info['variables'])
                ->field('name, value')
                ->select();
        }
        return $info;
    }


}
